package com.example.e_comm.controller;

import com.example.e_comm.entity.User;
import com.example.e_comm.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表 (list)
     * GET /api/users
     */
//    @GetMapping
//    public ResponseEntity<Map<String, Object>> listUsers() {
//        List<User> users = userService.getAllUsers();
//        Map<String, Object> response = new HashMap<>();
//        response.put("code", 200);
//        response.put("data", users);
//        response.put("message", "获取用户列表成功");
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 分页获取用户 (page)
//     * GET /api/users/page?current=1&size=10
//     */
//    @GetMapping("/page")
//    public ResponseEntity<Map<String, Object>> pageUsers(
//            @RequestParam(defaultValue = "1") int current,
//            @RequestParam(defaultValue = "10") int size) {
//        IPage<User> userPage = userService.getUsersPage(current, size);
//
//        Map<String, Object> response = new HashMap<>();
//        response.put("code", 200);
//        response.put("data", userPage.getRecords());
//        response.put("current", userPage.getCurrent());
//        response.put("size", userPage.getSize());
//        response.put("total", userPage.getTotal());
//        response.put("pages", userPage.getPages());
//        response.put("message", "分页获取用户成功");
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 根据ID获取用户 ({id})
//     * GET /api/users/{id}
//     */
//    @GetMapping("/{id}")
//    public ResponseEntity<Map<String, Object>> getUserById(@PathVariable Long id) {
//        User user = userService.getUserById(id);
//        Map<String, Object> response = new HashMap<>();
//        if (user != null) {
//            response.put("code", 200);
//            response.put("data", user);
//            response.put("message", "获取用户成功");
//        } else {
//            response.put("code", 404);
//            response.put("message", "用户不存在");
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 创建用户 (create)
//     * POST /api/users
//     */
//    @PostMapping
//    public ResponseEntity<Map<String, Object>> createUser(@RequestBody User user) {
//        User savedUser = userService.createUser(user);
//        Map<String, Object> response = new HashMap<>();
//        response.put("code", 200);
//        response.put("data", savedUser);
//        response.put("message", "创建用户成功");
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 删除用户 (delete{id})
//     * DELETE /api/users/{id}
//     */
//    @DeleteMapping("/{id}")
//    public ResponseEntity<?> register(@PathVariable Long id) {
//        boolean result = userService.deleteUser(id);
//        Map<String, Object> response = new HashMap<>();
//        if (result) {
//            response.put("code", 200);
//            response.put("message", "删除用户成功");
//        } else {
//            response.put("code", 404);
//            response.put("message", "用户不存在");
//        }
//        return ResponseEntity.ok(response);
//    }


    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            boolean result = userService.register(user);
            if (result) {
                return ResponseEntity.ok("注册成功");
            } else {
                return ResponseEntity.ok("注册失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody String username
            , @RequestBody String password) {
        try {
            String token = userService.login(username, password);
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            response.put("message", "登录成功");
            return ResponseEntity.ok(token);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        Logger logger = LoggerFactory.getLogger(UserController.class);
        logger.info("当前用户信息：{}" , userService.getUserByToken(token));
        try {
            String clean = token.replace("Bearer ", "");
            logger.info("当前用户信息：{}" , userService.getUserByToken(clean));

            User user = userService.getUserByToken(clean);
            if (user != null) {
                user.setPassword(null);
                return ResponseEntity.ok(user);
            } else {
                logger.warn ("没有找到用户Token");
                return ResponseEntity.status(401).body("没有找到用户Token");
            }
        } catch (Exception e) {
            logger.error("请求错误：",e );
            return ResponseEntity.status(400).body("请求错误" + e.getMessage());
        }
        }

    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader("Authorization") String token) {
        try {
            boolean result = userService.logout(token.replace("Bearer ", ""));
            if (result) {
                return ResponseEntity.ok("注销成功");
            } else {
                return ResponseEntity.ok("注销失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}